/**
 * Created by xiewei on 15/八月/13.
 */
//截取url后缀
var demandId = '';
var stop = null;
var imgDir = 'img/';
var petSexIcon = {
    boy: 'icon_pet_boy.png',
    girl: 'icon_pet_girl.png'
}
//获取邮编
getRegionCode();
var getRegionTimer = setInterval(function(){
    if(root){
        clearInterval(getRegionTimer);
    }else{
        getRegionCode();
    }
},50);
/**
 * 获取用户信息
 */
loading();
demandId = getUrlParam('demandId');
//获取用户信息
var demandReqData = {
    demandId: demandId,
    jd: '',
    wd: ''
}
/**
 * 禁止页面滚动
 */
var stopScroll = function(){
    banFlag = true;
    $("#img_slide_cover")[0].scrollTop = "0px";
    document.getElementById("img_slide_cover").scrollTop = 0;
    document.documentElement.style.overflow = "hidden";
    document.body.style.overflow = "hidden";
    document.addEventListener("touchmove",function(e){
        if(banFlag){
            e.preventDefault;
            e.returnValue = false;
            e.stopPropagation();
            return false;
        }
    });
}
/**
 * 恢复页面滚动
 */
var restartScroll = function(){
    document.documentElement.scrollTop = stop;
    document.body.scrollTop = stop;
    document.documentElement.style.overflowY = "auto";
    document.body.style.overflowY = "auto";
    banFlag = false;
}
/**
 * 查看大图
 * @param imgList
 * @param i
 */
function showImg(imgList,i){
    stop = document.documentElement.scrollTop == 0 ? document.body.scrollTop : document.documentElement.scrollTop;
    var width = getPageWidth();
    var height = getPageHeight();
    //显示遮罩
    $("#img_slide_cover").css({
        "height": height
    }).removeClass("hidden").animate({
        opacity: "1"
    },300);
    //拼图片展示相关节点
    var slides = $("#slides");
    height = height-50;
    imgList.each(function(){
        var img = $("<img>").attr("src",$(this).attr("bigsrc")).hide();
        var imgTimer = setInterval(function(){
            if(img[0].complete){
                clearInterval(imgTimer);
                //图片定位
                if(img[0].height/img[0].width > height/width){
                    var imgWidth = height/img[0].height*img[0].width;
                    img.css({
                        height: height,
                        width: imgWidth,
                        marginLeft: width/2-imgWidth/2
                    });
                }else{
                    var imgHeight = width/img[0].width*img[0].height;
                    img.css({
                        width: width,
                        height: imgHeight,
                        top : height/2-imgHeight/2
                    });
                }
            }
        },10);
        slides.append(img);
    });
    slides.slidesjs({
        heigth: height,
        start: i,
        navigation: false
    });
    slides.css("margin-top","25px");
    stopScroll();
}
/**
 * 查看大图设置
 */
var bigImgScale = 1;
var checkBigImg = function(){
    //图片滚动设置
    stopScroll();
    var imgList = $(".pic_list span");
    var width = getPageWidth();
    if(imgList.length == 1){
        var tempImg = $("<img>").attr("src",$(imgList[0]).attr("src"));
        var bigImgW = width*0.9;
        var imgTimer = setInterval(function(){
            if(tempImg[0].height && tempImg[0].height>0){
                clearInterval(imgTimer);
                bigImgScale =  tempImg[0].height/tempImg[0].width;
                var bigImgH = bigImgW*bigImgScale;
                $(imgList[0]).css({
                    width: bigImgW,
                    height: bigImgH
                });
            }
        },10);
    }
    $.each(imgList,function(i){
        if(imgList.length > 1){
            $(this).css({
                height: width*0.235
            });
        }
        $(this).bind("click",function(){
            showImg(imgList,i+1);
        });
    });
    $("#slides").click(function(){
        //关闭
        $("#img_slide_cover").animate({
            opacity: "0"
        },300);
        setTimeout("$('#img_slide_cover').addClass('hidden')",200);
        setTimeout("$('#slides').empty()",300);
        restartScroll();
    });
    restartScroll();
}

/**
 * 获取寄养需求详情
 */
var getDemandInfo = function(){
    $.ajax({
        url:'/dog2/appDemand/getDemandInfo',
        data: paramCoding(demandReqData),
        type: 'POST',
        dataType: 'json',
        success: function(res){
            if(res.respCode==0){
                $('#demandInfo').removeClass('hidden');
                //寄养需求当前状态
                var $state = $('#demandState');
                var stateContent = '';
                switch (res.flags){
                    case 1: stateContent = '需求进行中';break;
                    case 10: stateContent = '已完成';break;
                    case 14: stateContent = '已完成';break;
                    case 15: stateContent = '已完成';break;
                }
                $state.text(stateContent);
                //需求应答数
                if(res.respondCount){
                    $('#demandRespond').text('已有'+res.respondCount+'人应答');
                }else{
                    $('#demandRespond').text('已有0人应答');
                }
                //内容
                if(res.face){
                    $('#userFace').attr('src',res.face);
                }
                $('#demandTitle').text(res.title);
                $('#demandTime').html('<label class="orange">'+res.startTime+'</label> 至 <label class="orange">'+res.endTime+'</label>');
                $('#demandDays').text(getDemandDays(res.startTime,res.endTime));
                $('#demandDays').parent().removeClass('hidden');
                $('#demandRemark').text(res.remark);
                //图片
                var photoDiv = $('#demandPhotos');
                var shareImg = imgDir+'viptail_logo300.jpg';
                if(res.albumsList){
                    var photos = res.albumsList;
                    var width = (getPageWidth()-70)/3;
                    shareImg = photos[0].original+imgSize.thumbnail;
                    for(var i = 0; i < photos.length ; i ++){
                        var photo = photos[i];
                        var span = $('<span>').attr('src',photo.original+imgSize.thumbnail).attr('bigsrc',photo.original+imgSize.big)
                            .css({//先显示默认图片
                                width: width,
                                height: width*0.9,
                                background: 'url('+photo.original+imgSize.thumbnail+') no-repeat center center',
                                backgroundSize: 'cover'
                            }).appendTo(photoDiv);
                    }
                }
                setShareInfo('寄养需求'+res.title+'的详情', shareImg);
                //地址
                $('#demandAddress').text(res.address);
                //距离
                var demandMap = $('#demandMap');
                if(res.distance){
                    var dis = parseFloat(res.distance).toFixed(1);
                    dis = dis>100 ? '遥远' : dis+'km';
                    $('#demandDistance').text(dis);
                }
                demandMap.on('click',function(){
                    if(res.jd && res.wd){
                        //存在经纬度  可以打开地图查看
                        if(isWechat()){
                            //调用微信查看地图
                            wx.openLocation({
                                latitude: res.wd,
                                longitude: res.jd,
                                name: res.name,
                                address: res.address,
                                scale: 13,
                                infoUrl: ''
                            });
                        }else{
                            location.href = 'map.html?jd='+res.jd+'&wd='+res.wd;
                            setLocalStorage('name',res.title);
                            setLocalStorage('address',res.address);
                        }
                    }else{
                        return false;
                    }
                })
                //发布时间
                $('#demandCreateTime').text(res.createTime.split(' ')[0]+' 发布');
                //宠物列表
                var petUl = $('#demandPetList');
                var petList = res.petList;
                if(petList.length>0){
                    $('#demandPetTitle').removeClass('hidden');
                }
                for(var i=0; i<petList.length; i++){
                    var pet = petList[i];
                    //left
                    var left = $('<div>').addClass('left icon-pet');
                    if(pet.face){
                        $('<img>').addClass('img-circle').attr('src',pet.face).appendTo(left);
                    }else{
                        $('<img>').addClass('img-circle').attr('src',imgDir+iconImgs.pet).appendTo(left);
                    }
                    if(pet.sex==0){
                        //母的
                        $('<img>').addClass('icon-pet-sex').attr('src',imgDir+petSexIcon.girl).appendTo(left);
                    }else if(pet.sex==1){
                        $('<img>').addClass('icon-pet-sex').attr('src',imgDir+petSexIcon.boy).appendTo(left);
                    }
                    //right
                    var right = $('<div>').addClass('right');
                    right.append('<h1 class="inline">'+pet.name+'</h1><span class="ml15">'+pet.breed+'（'+pet.type+'）</span>');
                    //宠物年龄、绝育信息、免疫信息
                    var sterilization = '';//绝育
                    if(pet.sterilization==0){
                        sterilization = '未绝育'
                    }else if(pet.sterilization==1){
                        sterilization = '已绝育'
                    }
                    var petExplain = pet.ageYear+'岁('+pet.ageMonth+'个月)<label> | </label>'+sterilization;
                    if(pet.immunityType==2){
                        //免疫  0：未完善 1：已免疫 2：未免疫
                        petExplain += '<label> | </label>未免疫';
                    }else if(pet.immunityType==1){
                        petExplain += '<label> | </label>已免疫';
                    }
                    $('<p>').html(petExplain).appendTo(right);
                    if(i+1<petList.length){
                        var hr = $('<hr>');
                        $('<div>').addClass('demand-block').append(left,right,hr).appendTo(petUl);
                    }else{
                        $('<div>').addClass('demand-block pb15').append(left,right).appendTo(petUl);
                    }
                }
                //设置查看大图
                checkBigImg();
                $('#bottomImg').removeClass('hidden');
            }
            loaded();
            //表情转换
            emojifyTo($('#demandRemark'));//表情转换
        }
    })
}
getDemandInfo();
//地图设置
if(isWechat()){
    var wxData = { 'url': location.href };
    $.ajax({
        type: 'POST',
        async: false,
        dataType: 'json',
        url: '/dog2/wechatComm/weChatConfig',
        data: paramCoding(wxData),
        success: function (data) {
            wx.config({
                appId: data.appId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: ['getLocation','openLocation']
            });
            if(data.errResult){
                showMessageAlert(data.errMsg,11);
            }
        },
        error: function (data) {
            data = $.parseJSON(data['responseText']);
            showMessageAlert(data['message']);
        },
        cache: false
    });
}
